package com.yingpai.fitness.dvp_2_0.main.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.ContextUtil;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.register.RegisterBean;
import com.yingpai.fitness.dvp_2_0.main.util.XCountDownTimer;
import com.yingpai.fitness.dvp_2_0.main.util.NetWorkUtil;
import com.yingpai.fitness.dvp_2_0.main.util.encrypt.RsaEncrypt;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2018/11/6.
 */

public class RegisterActivity extends CommonActivity implements TextWatcher {
    @BindView(R.id.registerPhoneEt)
    EditText registerPhoneEt;
    @BindView(R.id.registerPasswordEt)
    EditText registerPasswordEt;
    @BindView(R.id.register_verification_code_et)
    EditText registerVerificationCodeEt;
    @BindView(R.id.registerVercodeTv)
    TextView registerVercodeTv;
    @BindView(R.id.registerInviteEt)
    EditText registerInviteEt;
    private String phoneNumber;
    private XCountDownTimer timer;
    private String registCode;
    private String passWord;
    private String beforeWord;
    private String specialWords = "-/:;()$&@\"_'`*#%[]{}!^￥+.,\\<>?~";//特殊字符专用串

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_register_layout);
    }

    @Override
    @OnClick({R.id.registerVercodeTv, R.id.goRegisterBtn, R.id.protocol, R.id.to_login, R.id.registerbackIv})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.registerVercodeTv:
                getVerCode();
                break;
            case R.id.goRegisterBtn:
                if (checkInfoComplete()) {
                    register();
                }
                break;
            case R.id.protocol:
                startActivity(ProtocolActivity.class);
                break;
            case R.id.to_login:
                startActivity(LoginActivity.class);
                break;
            case R.id.registerbackIv:
                finishActivity();
                break;
        }
    }

    private void register() {
        showDialog(this, "注册中...");
        String phoneNumsSec = "";
        String passwordSec = "";
        try {
            //加密
            phoneNumsSec = RsaEncrypt.getInstance(ContextUtil.getContext()).encryptWithBase64(phoneNumber);
            passwordSec = RsaEncrypt.getInstance(ContextUtil.getContext()).encryptWithBase64(passWord);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String inviteCode = registerInviteEt.getText().toString().trim() + "";

        HttpParams httpParams = new HttpParams();
        httpParams.put("phoneNo", phoneNumsSec);
        httpParams.put("password", passwordSec);
        httpParams.put("identifier", registCode);
        httpParams.put("inviteCode", inviteCode);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.REGISTER, httpParams, Url.REGISTER, new Callback<RegisterBean>() {
            @Override
            public void onSuccess(RegisterBean registerBean) {
                dismissDialog();
                if (Constant.REQUEST_SUCCESS.equals(registerBean.getResult())) {
                    EventBus.getDefault().postSticky("login," + phoneNumber + "," + passWord);
                    finishActivity();
                } else {
                    showToast(registerBean.getMsg());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void getVerCode() {
        showDialog(this, "获取中...");
        //先获取到填写的手机号
        phoneNumber = registerPhoneEt.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)) {
            //电话号是空的，吐司提示
            showToast("请填写手机号");
            registerPhoneEt.requestFocus();
        } else if (phoneNumber.length() != 11) {
            showToast("请填写正确的手机号");
        } else if (NetWorkUtil.isConnected() && NetWorkUtil.isAvailableByPing()) {
            String mPhoneNumber = "";
            try {
                mPhoneNumber = RsaEncrypt.getInstance(ContextUtil.getContext()).encryptWithBase64(phoneNumber);
            } catch (Exception e) {
                e.printStackTrace();
            }
            HttpParams httpParams = new HttpParams();
            httpParams.put("phoneNo", mPhoneNumber);
            finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_REGISTER_VERCODE, httpParams, Url.GET_REGISTER_VERCODE, new Callback<BaseResponse>() {
                @Override
                public void onSuccess(BaseResponse baseResponse) {
                    dismissDialog();
                    if (Constant.REQUEST_SUCCESS.equals(baseResponse.getResult())) {
                        timer = new XCountDownTimer(6 * 10000, 1000, registerVercodeTv, 1);
                        timer.start();
                        showToast(baseResponse.getMsg());
                    } else {
                        showToast(baseResponse.getMsg());
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dismissDialog();
                    //showToast("发送超时");
                }
            });
        } else {
            showToast("网络不可用，请检查网络设置");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    /**
     * 非空判断
     *
     * @return true：可以进行下一步  false：还有非法项
     */
    private boolean checkInfoComplete() {
        phoneNumber = registerPhoneEt.getText().toString().trim();
        if (!TextUtils.isEmpty(phoneNumber)) {
            //手机号不为空，进行下一步判断
            if (phoneNumber.length() == 11) {
                //手机号长度正确，进行下一步判断
                registCode = registerVerificationCodeEt.getText().toString().trim();
                if (!TextUtils.isEmpty(registCode)) {
                    //验证码正确，进行下一步判断
                    passWord = registerPasswordEt.getText().toString().trim();
                    if (!TextUtils.isEmpty(passWord)) {
                        //密码有东西
                        if (passWord.length() >= 6) {
                            //密码符合长度
                        } else {
                            //密码太短
                            showToast("请输入6-12位密码");
                            registerPasswordEt.requestFocus();
                            return false;
                        }
                    } else {
                        //密码为空
                        showToast("请输入密码");
                        registerPasswordEt.requestFocus();
                        return false;
                    }
                } else {
                    //验证码为空
                    showToast("请填写验证码");
                    registerVerificationCodeEt.requestFocus();
                    return false;
                }
            } else {
                //手机号长度错误
                showToast("请输入正确的手机号码");
                registerPhoneEt.requestFocus();
                return false;
            }
        } else {
            //手机号为空
            showToast("请输入手机号码");
            registerPhoneEt.requestFocus();
            return false;
        }
        return true;
    }


    /**
     * 编辑框文本改变之前
     *
     * @param s
     * @param start
     * @param count
     * @param after
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        beforeWord = s.toString();
    }

    /**
     * 文本改变中
     *
     * @param s
     * @param start
     * @param before
     * @param count
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    /**
     * 文本改变后
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        if (s.toString().equals(beforeWord)) {
            return;
        }
        if (!TextUtils.isEmpty(s.toString())) {
            for (int i = 0; i < s.toString().length(); i++) {
                if (specialWords.contains(s.toString().charAt(i) + "")) {
                    //发现了特殊字符，还原成之前的样子
                    registerPasswordEt.setText(beforeWord);
                    registerPasswordEt.setSelection(registerPasswordEt.getText().toString().length());
                    return;
                }
            }
        }
    }
}
